﻿@using TelerikedIn.Models;

@{
    ViewBag.Title = "Users Administration";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>@ViewBag.Title</h1>

@(Html.Kendo()
.Grid<TelerikedIn.WebApp.Areas.Administration.Models.UserDetailsVM>()
.Name("grid-users")
.DataSource(ds =>
{
    ds.Ajax()
    .ServerOperation(true)
    .PageSize(5)
    .Model(model =>
    {
        model.Id(u => u.Id);
    })
    .Events(events => events.Error("error"))
    .Read(read => read.Action("AllUsers", "Users"))
    .Update(update => update.Action("Update", "Users"));
})
.Sortable(sort =>
{
    sort.SortMode(GridSortMode.MultipleColumn).AllowUnsort(true);
})
.Pageable()
.Editable(edit =>
{
    edit.Enabled(true)
    .Mode(GridEditMode.PopUp)
    .Window(window =>
        {
            window.Actions(action =>
            {
                action.Close();
            });
        })
    .TemplateName("UserDetailsVM");
})
.Columns(columns =>
{
    columns.Bound(u => u.UserName);
    columns.Bound(u => u.FirstName);
    columns.Bound(u => u.LastName);
    columns.Bound(u => u.Country);
    columns.Bound(u => u.City);
    columns.Bound(u => u.Education);
    columns.Bound(u => u.IsBanned).ClientTemplate("<i class=\"#= IsBanned ? \"icon-ok\" : \"icon-remove\" #\"></i>");
    columns.Bound(u => u.IsAdmin).ClientTemplate("<i class=\"#= IsAdmin ? \"icon-ok\" : \"icon-remove\" #\"></i>");
    columns.Command(c =>
    {
        c.Edit().Text("Edit").UpdateText("Update").CancelText("Cancel");
    })
    .Title("Actions");
}))

@(Html.Kendo().Window()
    .Name("alertWindow")
    .Title("Errors")
    .Width(400)
    .Height(200)
    .Modal(true)
    .Visible(false)
)

<script>
    function showAlertWindow(message) {
        var alertWindow = $('#alertWindow').data('kendoWindow');
        alertWindow
            .content(message)
            .refresh()
            .center()
            .open();
    }

    function error(e) {
        if (e.errors) {
            var message = "";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "<br />";
                    });
                }
            });

            showAlertWindow(message);
            this.cancelChanges();
        }
    }
</script>

<script id="create-edit-user" type="text/x-kendo-template">
    <p>Edit user</p>
    <div class="k-edit-label">
        <label for="UserName">Username</label>
    </div>
    <input type="text" class="k-input k-textbox" name="UserName">
</script>